<template>
  <el-dialog
    center
    :visible.sync="dialogVisible"
    width="1000px"
    title="代理商信息"
    append-to-body
    :before-close="handleClose"
    :close-on-click-modal="false"
  >
    <div
      class="agene"
      v-show="areaTrigger"
    >
      <div style="display: flex; justify-content: space-between">
        <p style="margin-left: 20px;">选择区域</p>
        <i
          @click="areaTrigger = false"
          style="margin:15px 15px 0 0;cursor: pointer;"
          class="el-icon-close"
        ></i>
      </div>
      <div>
        <hsk-address-sel
          style="margin-left:20px"
          :inputNumShow="inputNumShow"
          :inputInterval="inputInterval"
          @addressChange="addressChanges"
          :defaultAddress="[]"
        />
      </div>
      <el-button
        style="margin-left:130px;margin-top:20px;"
        type="primary"
        @click="sureArea"
      >确定添加代理区域</el-button>
    </div>
    <el-row :gutter="10">
      <el-col :span="7">
        <div style="display: flex; flex-direction: column">
          <div
            class="up_sy_logo_div"
            style="margin-left: 15px;"
          >
            <!--支持点击查看大图-->
            <el-image
              v-if="ruleForm.hrefn"
              style="width:250px;height:175px;"
              :src="ruleForm.hrefn"
              :preview-src-list="ruleForm.hrefn ? [ruleForm.hrefn] : []"
            ></el-image>
          </div>
          <el-upload
            :accept="pic_accept"
            :action="uploadFileUrl + '/file/saveFile'"
            :before-upload="beforeAvatarUpload"
            :on-success="handleLicenseSuccess"
            :data="{fileRemark: '', fileuserInfo: ''}"
            :show-file-list="false"
          >
            <el-button
              style="margin:10px 0 0 90px;"
              size="small"
              :disabled="disabled"
              type="primary"
            >上传营业执照</el-button>
          </el-upload>
        </div>
      </el-col>
      <el-form
        ref="elForm"
        :model="formData"
        size="small"
        label-width="100px"
        :rules="rules"
        :disabled="disabled"
      >
        <el-col :span="10">
          <el-form-item
            label="代理商名称"
            prop="agentName"
          >
            <el-input
              v-model="formData.agentName"
              placeholder="请输入代理商名称"
              clearable
              :disabled="editorsave == 2"
              :style="{width: '100%'}"
              @blur="handleBlur('agentName')"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="代理商类型">
            <el-radio-group v-model="formData.agentType">
              <el-radio label="2">经销</el-radio>
              <el-radio label="1">直销</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item
            label="统一社会信用代码"
            prop="creditCode"
          >
            <el-input
              v-model="formData.creditCode"
              placeholder="请输入统一社会信用代码"
              clearable
              maxlength="19"
              :disabled="editorsave == 2"
              :style="{width: '100%'}"
              @blur="handleBlur('creditCode')"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item
            label="负责人"
            prop="responsiblePerson"
          >
            <el-input
              v-model="formData.responsiblePerson"
              placeholder="请输入负责人"
              clearable
              :style="{width: '100%'}"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item
            label="联系电话"
            prop="agentPhone"
          >
            <el-input
              v-model="formData.agentPhone"
              placeholder="请输入联系电话"
              maxlength="11"
              clearable
              :style="{width: '100%'}"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item
            label="负责人电话"
            prop="responsibleTel"
          >
            <el-input
              v-model="formData.responsibleTel"
              placeholder="请输入负责人电话"
              maxlength="11"
              clearable
              :style="{width: '100%'}"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="代理区域"
            prop="agentArea"
          >
            <div class="tagBox">
              <el-tag
                v-for="tag in tags"
                :key="tag.name"
                :closable="!disabled"
                style="margin-left:10px;"
                @close="handleCloseTag(tag)"
              >
                {{tag.name}}
              </el-tag>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-button
            type="primary"
            @click="addDlArea"
          >新增代理区域</el-button>
        </el-col>
        <el-col :span="7">
          <el-form-item
            label="注册资本"
            prop="registerFund"
          >
            <el-input
              v-model="formData.registerFund"
              placeholder="请输入注册资本"
              type="number"
              min="0"
              :style="{width: '100%'}"
              @blur="handleFundBlur($event, 'registerFund')"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <p style="margin-top:7px;">万元</p>
        </el-col>
        <el-col :span="7">
          <el-form-item
            label="实缴资本"
            prop="realFund"
          >
            <el-input
              v-model="formData.realFund"
              placeholder="请输入实缴资本"
              type="number"
              min="0"
              :style="{width: '100%'}"
              @blur="handleFundBlur($event, 'realFund')"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <p style="margin-top:7px;">万元</p>
        </el-col>
        <el-col :span="7">
          <el-form-item
            label="代理商状态"
            prop="currentStatus"
          >
            <el-switch
              active-text="启用"
              active-value="0"
              inactive-value="1"
              inactive-text="停用"
              v-model="formData.currentStatus"
            ></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <div style="margin-left: 32px;">
            <div class="gd_info">股东信息</div>
            <el-table
              :data="formData.shareholderInfoDtoList"
              style="width: 100%"
            >
              <el-table-column
                prop="shareholderName"
                label="股东名称"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'shareholderInfoDtoList.' + scope.$index + '.shareholderName'"
                    :rules="{ required: true, message: '请输入内容', trigger: 'blur' }"
                  >
                    <el-input
                      v-model="scope.row.shareholderName"
                      placeholder="请输入内容"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="shareRatio"
                label="持股比例（%）"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'shareholderInfoDtoList.' + scope.$index + '.shareRatio'"
                    :rules="{ required: true, message: '请输入内容', trigger: 'blur' }"
                  >
                    <el-input
                      v-model.number="scope.row.shareRatio"
                      placeholder="请输入内容"
                      type="number"
                      min="0"
                      @blur="handleFundItemBlur(scope.row, 'shareRatio', '2')"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="paidinFund"
                label="认缴出资（万元）"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'shareholderInfoDtoList.' + scope.$index + '.paidinFund'"
                    :rules="{ required: true, message: '请输入内容', trigger: 'blur' }"
                  >
                    <el-input
                      v-model.number="scope.row.paidinFund"
                      placeholder="请输入内容"
                      type="number"
                      min="0"
                      @blur="handleFundItemBlur(scope.row, 'paidinFund', '1')"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="paidCapital"
                label="实缴出资（万元）"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'shareholderInfoDtoList.' + scope.$index + '.paidCapital'"
                    :rules="{ required: true, message: '请输入内容', trigger: 'blur' }"
                  >
                    <el-input
                      v-model.number="scope.row.paidCapital"
                      placeholder="请输入内容"
                      type="number"
                      min="0"
                      @blur="handleFundItemBlur(scope.row, 'paidCapital', '1')"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="idNumber">
                <template slot="header">
                  <div class="table-label">
                    身份证号码
                  </div>
                </template>
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'shareholderInfoDtoList.' + scope.$index + '.idNumber'"
                    :rules="{ required: true, message: '请输入身份证号码', trigger: 'blur' }"
                  >
                    <el-input
                      v-model="scope.row.idNumber"
                      placeholder="请输入内容"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="address"
                label="身份证图片正面"
              >
                <template slot-scope="scope">
                  <el-form-item>
                    <div style="display: flex; flex-direction: column">
                      <div class="up_sy_logo_div">
                        <el-image
                          style="width:100px;height:70px;"
                          :src="scope.row.hrefnFront || hrefn"
                          :preview-src-list="scope.row.hrefnFront ? [scope.row.hrefnFront] : [hrefn]"
                        ></el-image>
                      </div>
                      <el-upload
                        :accept="pic_accept"
                        :action="uploadFileUrl + '/file/saveFile'"
                        :before-upload="beforeAvatarUpload"
                        :on-success="(response, file) => handleFrontSuccess(response, file, scope.row)"
                        :data="{fileRemark: '', fileuserInfo: ''}"
                        :show-file-list="false"
                      >
                        <el-button
                          type="primary"
                          :disabled="disabled"
                          size="small"
                          style="margin: 2px 13px 0;"
                        >上传<i class="el-icon-upload el-icon--right"></i></el-button>
                      </el-upload>
                    </div>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="address"
                label="身份证图片反面"
              >
                <template slot-scope="scope">
                  <el-form-item>
                    <div style="display: flex; flex-direction: column">
                      <div class="up_sy_logo_div">
                        <el-image
                          style="width:100px;height:70px;"
                          :src="scope.row.hrefnBack || hrefn"
                          :preview-src-list="scope.row.hrefnBack ? [scope.row.hrefnBack] : [hrefn]"
                        ></el-image>
                      </div>
                      <el-upload
                        :accept="pic_accept"
                        :action="uploadFileUrl + '/file/saveFile'"
                        :before-upload="beforeAvatarUpload"
                        :on-success="(response, file) => handleBackSuccess(response, file, scope.row)"
                        :data="{fileRemark: '', fileuserInfo: ''}"
                        :show-file-list="false"
                      >
                        <el-button
                          type="primary"
                          :disabled="disabled"
                          size="small"
                          style="margin: 2px 13px 0;"
                        >上传<i class="el-icon-upload el-icon--right"></i></el-button>
                      </el-upload>
                    </div>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="操作" v-if="!disabled">
                <template slot-scope="scope">
                  <el-button @click="deleteRow(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button
              style="margin:10px 0 10px 43%;"
              @click="addRow"
              type="primary"
            >添加股东信息</el-button>
          </div>
        </el-col>
        <el-col :span="24" style="margin-top: 10px;">
          <el-form-item
            label="保证金组成说明"
            prop="depositCompose"
          >
            <el-input
              v-model="formData.depositCompose"
              type="textarea"
              placeholder="请输入保证金组成说明"
              :autosize="{minRows: 4, maxRows: 4}"
              :style="{width: '100%'}"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <p style="font-size:18px; color:#303133; margin-top: -10px;">开票信息</p>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="发票抬头"
            prop="invoiceTitle"
          >
            <el-input
              v-model="formData.invoiceTitle"
              placeholder="请输入发票抬头"
              clearable
              :style="{width: '100%'}"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="税号"
            prop="taxNo"
          >
            <el-input
              v-model="formData.taxNo"
              placeholder="请输入税号"
              clearable
              :style="{width: '100%'}"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="联系电话"
            prop="invoiceTle"
          >
            <el-input
              v-model="formData.invoiceTle"
              placeholder="请输入联系电话"
              clearable
              :style="{width: '100%'}"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="开户行"
            prop="invoiceBank"
          >
            <el-input
              v-model="formData.invoiceBank"
              placeholder="请输入开户行"
              clearable
              :style="{width: '100%'}"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="银行账号"
            prop="invoiceAccount"
          >
            <el-input
              v-model="formData.invoiceAccount"
              placeholder="银行账号"
              clearable
              :style="{width: '100%'}"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item
            label="地址"
            prop="invoiceAddress"
          >
            <el-input
              v-model="formData.invoiceAddress"
              placeholder="请输入地址"
              clearable
              :style="{width: '100%'}"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <p style="font-size:18px; color:#303133; margin-top: -5px;">代理商地址（文件邮寄）</p>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="收件人名称"
            prop="recipientName"
          >
            <el-input
              v-model="formData.recipientName"
              placeholder="请输入收件人名称"
              clearable
              :style="{width: '50%'}"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          :pull="0"
        >
          <el-form-item
            label="收件人电话"
            prop="recipientPhone"
          >
            <el-input
              v-model="formData.recipientPhone"
              placeholder="请输入收件人电话"
              maxlength="11"
              clearable
              :style="{width: '50%'}"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <hsk-address-sel
            :addressShow="addressShow"
            :inputNumShow="inputNumShow"
            :inputInterval="inputInterval"
            @addressChange="addressChange"
            :defaultAddress="defaultAddress"
          />
        </el-col>
        <el-col
          :span="12"
          :pull="0"
        >
          <el-form-item
            label="电子邮箱"
            prop="agentEmail"
          >
            <el-input
              v-model="formData.agentEmail"
              placeholder="请输入电子邮箱"
              clearable
              :style="{width: '50%'}"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="24"
          :pull="0"
        >
          <el-form-item
            label="详细地址"
            prop="detailedAddress"
          >
            <el-input
              v-model="formData.detailedAddress"
              placeholder="请输入详细地址"
              clearable
              :style="{width: '100%'}"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <p style="font-size:18px; color:#303133; margin-top: -5px;">其他材料</p>
        </el-col>
        <div
          v-if="disabled"
          style="margin-bottom: 10px;"
        >
          <el-table
            :data="listData"
            ref="table"
            stripe
            border
            style="width: 100%;margin-top: 10px;"
          >
            <el-table-column
              label="序号"
              width="80"
            >
              <template #default="scope">{{ scope.$index + 1 }}</template>
            </el-table-column>
            <el-table-column
              label="附件名称"
              show-overflow-tooltip
              width="200"
              prop="fileName"
            >
            </el-table-column>
            <el-table-column
              label="附件说明"
              show-overflow-tooltip
              prop="fileRemark"
            ></el-table-column>
            <el-table-column
              label="附件类型"
              show-overflow-tooltip
              width="100"
              prop="fileType"
            >
            </el-table-column>
            <el-table-column
              label="操作"
              width="150"
            >
              <template #default="scope">
                <el-button
                  type="text"
                  :disabled="false"
                  @click="handleDownloadFile(scope.row)"
                >下载</el-button>
                <el-button
                  type="text"
                  :disabled="false"
                  @click="handlePreviewFile(scope.row)"
                >预览</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <template v-else>
          <div
            v-for="(item,index) in listData"
            :key="index"
            style="margin-bottom: 10px;"
          >
            <el-col
              style="margin-left:-14px"
              :span="7"
            >
              <el-form-item
                label="附件名称"
                prop="fileName"
              >
                <el-input
                  v-model="item.fileName"
                  placeholder="请输入附件名称"
                  clearable
                  :style="{width: '100%'}"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item
                label="附件说明"
                prop="fileRemark"
              >
                <el-input
                  v-model="item.fileRemark"
                  placeholder="请输入附件说明"
                  clearable
                  :style="{width: '100%'}"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col
              :span="7"
              style="display: flex;"
            >
              <el-form-item label="附件上传">

              </el-form-item>
              <el-upload
                class="upload-demo"
                :ref="'uploadFile' + index"
                :accept="fileAccept"
                :action="uploadFileUrl + '/file/saveFile'"
                :before-upload="beforeUpload"
                :on-change="(file, fileList) => handleChange(file, fileList, item)"
                :on-success="(response, file, fileList) => handleSuccess(response, file, fileList, item, index, 'uploadFile' + index)"
                :on-remove="(file, fileList) => handleRemove(file, fileList, item)"
                :file-list="item.fileList"
                :data="{fileRemark: item.fileRemark, fileuserInfo: item.fileName}"
                :multiple="false"
                :auto-upload="true"
                style="width: 90%;"
              >
                <!-- :limit="1" -->
                <el-button
                  size="small"
                  type="primary"
                >点击上传</el-button>
              </el-upload>
            </el-col>
            <el-col :span="3">
              <el-button
                @click="deleteList(index)"
                style="margin-bottom: 20px;"
              >删除</el-button>
            </el-col>
          </div>
          <el-button
            style="margin:-15px 0 10px 43%;"
            @click="addList"
            type="primary"
          >添加附件列表</el-button>
        </template>

        <el-col :span="24">
          <p style="font-size:18px; color:#303133; margin-top: -5px;">登录账户信息</p>
        </el-col>
        <el-col
          :span="12"
          style="margin-left:-14px"
        >
          <el-form-item
            label="登录账号"
            prop="userName"
          >
            <el-input
              v-model="formData.userName"
              placeholder="请输入登录账号"
              clearable
              :disabled="editorsave == 2"
              :style="{width: '100%'}"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="登录密码"
            prop="passWord"
          >
            <el-input
              v-model="formData.passWord"
              type="text"
              placeholder="请输入登录密码"
              clearable
              class="no-autofill-pwd"
              :disabled="editorsave == 2"
              :style="{width: '100%'}"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <div slot="footer">
      <el-button
        v-show="saveBtn"
        type="primary"
        @click="handleConfirm('elForm')"
      >保存</el-button>
    </div>
    <PreviewFile
      :fileType="fileType"
      :fileUrl="fileUrl"
      :dialogVisible="dialogFileVisible"
      @cancel="dialogFileVisible = false"
    />
  </el-dialog>
</template>

<script>
import { addAgent, update, detail, queryFiles, agentcheck } from '@/api/agent/index'
import HskAddressSel from '@/components/area/index.vue'
import { downloadFile, previewFile } from '@/utils/utils';

import { passwordValidDict } from '@/api/password'
import PreviewFile from '@/components/PreviewFile/index'
import { validatePhone, validateEmail, validateNumber } from '@/utils/validate'
export default {
  dicts: ['sys_accept_type', 'enabled_file_upload_types'],
  components: {
    HskAddressSel,
    PreviewFile
  },
  data() {
    const passWordValidator = (rule, value, callback) => {
      if (rule.required) {
        if (value === '') {
          callback(new Error('请输入登录密码'))
        } else {
          passwordValidDict().then(res => {
            const { data } = res;
            const regularExpression = new RegExp(data.regular);
            if (!regularExpression.test(value)) {
              callback(new Error(data.illustration));
            } else {
              callback();
            }
          })
        }
      } else {
        callback();
      }
    }

    const creditCodeValidator = (rule, value, callback) => {
      if (rule.required) {
        if (value === '') {
          callback(new Error('请输入统一社会信用代码'))
        } else {
          agentcheck({
            creditCode: value
          }).then(res => {
            if (res.data) {
              callback(new Error('统一社会信用代码重复'));
            } else {
              callback();
            }
          })
        }
      } else {
        callback();
      }
    }
    return {
      dialogVisible: false,

      uploadFileUrl: process.env.VUE_APP_BASE_API,
      saveBtn: true,
      closable: false,
      areaTrigger: false,
      disabled: false,
      tags: [],
      inputNumShow: 4,
      inputInterval: 10,
      listData: [
        {
          fileName: '',
          fileUuid: '',
          fileRemark: '',
          fileList: []
        }
      ],
      // 用于追踪新增行的状态
      newRow: {
        paidCapital: "",
        paidinFund: "",
        shareRatio: "",
        shareholderName: ""
      },
      // 用于追踪新增行的状态
      newRows: {
        fileuserInfo: '',
        file: '',
        fileRemark: '',
        fileList: []
      },
      // 表单参数
      formData: {
        agentType:'2',//代理商类型
        agentEmail:'',//电子邮箱
        agentName: "",
        responsiblePerson: "",
        creditCode: "",
        currentStatus: "0",
        responsibleTel: "",
        agentPhone: "",
        registerFund: 0,
        realFund: 0,
        depositCompose: "",
        invoiceTitle: "",
        taxNo: "",
        invoiceAddress: "",
        invoiceTle: "",
        invoiceBank: "",
        invoiceAccount: "",
        shareholderInfoDtoList: [],
        agentAreaInfoDtoList: [],
        detailedAddress: "",
        recipientName: "",
        recipientPhone: "",
        userName: "",
        nickName: "固定测试",
        licensefileId: "",
        annexId: "",
        mailProv: "",
        mailCity: "",
        mailArea: "",
        mailTown: "",
        roleName: "",
        roleKey: "",
        roleStatus: '0',
        deptName: "",
        passWord: ""
      },
      rules: {
        agentEmail:[{ required: true, validator: validateEmail, trigger: 'blur' }],
        agentName: [{
          required: true,
          message: '请输入代理商名称',
          trigger: 'blur'
        }],
        responsiblePerson: [{
          required: true,
          message: '请输入负责人',
          trigger: 'blur'
        }],
        creditCode: [{ required: true, validator: creditCodeValidator, trigger: 'blur' }],
        agentPhone: [{
          required: true,
          validator: validatePhone,
          trigger: 'blur'
        }],
        responsibleTel: [{
          required: true,
          validator: validatePhone,
          trigger: 'blur'
        }],
        depositCompose: [{
          required: true,
          message: '请输入保证金组成说明',
          trigger: 'blur'
        }],
        detailedAddress: [{
          required: true,
          message: '请输入详细地址',
          trigger: 'blur'
        }],
        recipientPhone: [{
          required: true,
          validator: validatePhone,
          trigger: 'blur'
        }],
        recipientName: [{
          required: true,
          message: '请输入收件人名称',
          trigger: 'blur'
        }],
        userName: [{
          required: true,
          message: '请输入登录账号',
          trigger: 'blur'
        }],
        passWord: [
          { required: true, validator: passWordValidator, trigger: 'blur' }
        ]
      },
      //  :rules="rules"
      pic_accept: ".jpg,.png,.jpeg,.bmp",
      pic_maxsize: 10,//单位MB
      ruleForm: {
        hrefn: require("@/assets/images/space.png")
      },
      hrefn: require("@/assets/images/space.png"),
      file: [],//暂存文件
      submitLoading: false,//防止重复提交
      fileList: [],
      allArea: [],
      moreArea: [],
      editorsave: 1,
      defaultAddress: [],
      fileAccept: '',
      fileUrl: '',
      fileType: '',
      dialogFileVisible: false,
      addressShow: false
    }
  },
  watch: {
    'dict.type.enabled_file_upload_types': {
      deep: true,
      handler(newValue) {
        if (newValue && newValue.length > 0) {
          this.fileAccept = newValue.map(item => {
            let updatedValue = item.value.split(',').map(item => `.${item}`).join(',');
            return updatedValue;
          }).join(',');
        }
      },
      immediate: true,
    }
  },
  methods: {
    sync(row, flag) {
      this.addressShow = false
      this.dialogVisible = true
      this.disabled = flag;
      this.saveBtn = !flag
      this.closable = !flag
      if (row) {
        this.editorsave = 2
        this.closable = true;
        this.tags = []
        if (this.$refs.elForm) {
          this.$nextTick(() => {
            this.$refs.elForm.clearValidate()
          })
        }

        this.rules.passWord[0].required = false
        this.rules.creditCode[0].required = false
        this.ruleForm.hrefn = require("@/assets/images/space.png")
        detail({
          agentId: row.agentId
        }).then(response => {
          this.defaultAddress = [response.data.mailProv, response.data.mailCity, response.data.mailArea, response.data.mailTown]
          response.data.passWord = response.data.passWord || ''
          this.addressShow = true
          this.formData.detailedAddress = response.data.detailedAddress || ''
          this.formData = response.data;
          this.listData = response.data.annexIdList.map(item => {
            return {
              ...item,
              fileList: [{
                name: item.fileName,
                url: item.filePath,
                status: 'success'
              }]
            }
          })

          this.formData.realFund = Number((this.formData.realFund / 10000).toFixed(4));
          this.formData.registerFund = Number((this.formData.registerFund / 10000).toFixed(4));
          this.formData.shareholderInfoDtoList.map(item => {
            item.paidCapital = Number((item.paidCapital / 10000).toFixed(4));
            item.paidinFund = Number((item.paidinFund / 10000).toFixed(4));
            item.shareRatio = Number(item.shareRatio);
            return item
          });


          response.data.agentAreaInfoDtoList.forEach(item => {
            const { agentAddressPro, agentAddressCity, agentAddressCounty, agentAddressTown } = item
            this.tags.push({
              name: (agentAddressPro || '') + (agentAddressCity || '') + (agentAddressCounty || '') + (agentAddressTown || '')
            })
          })
          this.formData.agentAreaInfoDtoList = response.data.agentAreaInfoDtoList
          this.updateShareholderInfo(response)

          if (response.data.licensefileId.length > 0) {
            queryFiles({
              fileId: response.data.licensefileId,
              modelKey: 'original'
            }).then(res => {
              const blob = new Blob([res], { type: "image/jpeg" })
              const fileUrl = window.URL.createObjectURL(blob);
              this.ruleForm.hrefn = fileUrl
            })
          }
        })
      } else {
        this.closable = true;
        this.editorsave = 1;
        if (this.$refs.elForm) {
          this.$nextTick(() => {
            this.$refs.elForm.clearValidate()
          })
        }
        this.listData = [
          {
            fileName: '',
            fileUuid: '',
            fileRemark: '',
            fileList: []
          }
        ]
        this.formData = {
          agentType:'2',//代理商类型
          agentEmail:'',//电子邮箱
          agentName: "",
          responsiblePerson: "",
          creditCode: "",
          currentStatus: "0",
          responsibleTel: "",
          agentPhone: "",
          registerFund: 0,
          realFund: 0,
          depositCompose: "",
          invoiceTitle: "",
          taxNo: "",
          invoiceAddress: "",
          invoiceTle: "",
          invoiceBank: "",
          invoiceAccount: "",
          shareholderInfoDtoList: [],
          agentAreaInfoDtoList: [],
          detailedAddress: "",
          recipientName: "",
          recipientPhone: "",
          userName: "",
          nickName: "固定测试",
          licensefileId: "",
          annexId: "",
          mailProv: "",
          mailCity: "",
          mailArea: "",
          mailTown: "",
          roleName: "",
          roleKey: "",
          roleStatus: '0',
          deptName: "",
          passWord: ""
        }
        this.ruleForm.hrefn = require("@/assets/images/space.png")
        this.tags = [];
        this.saveBtn = true;
        this.rules.passWord[0].required = true
        this.rules.creditCode[0].required = true
        this.defaultAddress = []
      }
    },
    handleClose() {
      this.dialogVisible = false
    },
    handleBlur(name) {
      if (name === 'agentName') {
        this.formData.invoiceTitle = this.formData[name]
      }
      if (name === 'creditCode') {
        this.formData.taxNo = this.formData[name]
      }
    },
    handleFundItemBlur(row, fieldName, type) {
      if (typeof row[fieldName] === 'number') {
        if (type === '1') {
          row[fieldName] = parseFloat(row[fieldName].toFixed(4));
        } else {
          row[fieldName] = parseFloat(row[fieldName].toFixed(2));
        }
      }
    },
    handleFundBlur(e, type) {
      this.formData[type] = e.target.valueAsNumber.toFixed(4)
    },
    async updateShareholderInfo(response) {
      const updatedList = [];

      for (const item of response.data.shareholderInfoDtoList) {
        const frontResult = await queryFiles({
          fileId: item.idcardfileId || '',
          modelKey: 'original'
        });
        const backResult = await queryFiles({
          fileId: item.idcardfilereId || '',
          modelKey: 'original'
        });

        const frontBlob = new Blob([frontResult], { type: "image/jpeg" });
        const backBlob = new Blob([backResult], { type: "image/jpeg" });
        const frontUrl = item.idcardfileId.length ? window.URL.createObjectURL(frontBlob) : this.hrefn;
        const backUrl = item.idcardfilereId.length ? window.URL.createObjectURL(backBlob) : this.hrefn;

        updatedList.push({
          ...item,
          hrefnFront: frontUrl,
          hrefnBack: backUrl
        });
      }

      // 更新 formData 属性
      this.formData.shareholderInfoDtoList = updatedList;
    },
    // 文件下载
    async handleDownloadFile(row) {
      downloadFile({ fileUuid: row.fileUuid });
    },
    // 文件预览
    async handlePreviewFile(row) {
      try {
        const { arrayBuffer, fileType } = await previewFile({ fileUuid: row.fileUuid });
        this.fileUrl = arrayBuffer;
        this.fileType = fileType;
        this.dialogFileVisible = true
      } catch (error) {
        this.$modal.msgError(error.message);
      }
    },
    beforeUpload(file) {
      if (file.size / 1024 / 1024 > 50) {
        this.$message.error('文件不能超过50M！');
        return false;
      }
      return true;
    },
    handleChange(file, fileList, v) {
      if (fileList.length > 0) {
        v.fileList = [fileList[fileList.length - 1]];
      } else {
        v.fileList = [];
      }
      return true
    },
    handleSuccess(response, file, fileList, v, i, uploadName) {
      let uid = file.uid
      let idx = this.$refs[uploadName][0].uploadFiles.findIndex(item => item.uid == uid)
      if (response.code != 200) {
        this.$modal.msgError('文件格式或命名存在特殊字符,请检查后重新上传!');
        this.$refs[uploadName][0].uploadFiles.splice(idx, 1)
        return true;
      }

      const { fileName: originalFileName, fileUuid } = response.data;
      v.fileName = originalFileName.split('.').shift();
      v.fileUuid = fileUuid;
      v.fileList.push(file);
    },
    handleRemove(file, fileList, v) {
      v.fileList = fileList
      if (!v.fileList.length) {
        v.fileName = ''
        v.fileUuid = ''
      }
    },

    addressChange(e) {
      this.formData.detailedAddress = e.filter(item => item != '').length ? e.join("") : this.formData.detailedAddress
      this.formData.mailProv = e[0] || ''
      this.formData.mailCity = e[1] || ''
      this.formData.mailArea = e[2] || ''
      this.formData.mailTown = e[3] || ''
    },
    addDlArea() {
      this.areaTrigger = true;
    },
    addressChanges(e) {
      this.allArea = e.join("")
      this.moreArea = e;
    },
    handleCloseTag(tag) {
      this.tags.splice(this.tags.indexOf(tag), 1);
      this.formData.agentAreaInfoDtoList.splice(this.tags.indexOf(tag), 1);
    },
    sureArea() {
      this.formData.agentAreaInfoDtoList.push({
        agentAddressPro: this.moreArea[0] || '',
        agentAddressCity: this.moreArea[1] || '',
        agentAddressCounty: this.moreArea[2] || '',
        agentAddressTown: this.moreArea[3] || '',
      })
      this.tags.push({
        name: this.allArea
      })
      this.areaTrigger = false;
    },
    addRow() {
      const newRow = { paidCapital: '', paidinFund: '', shareRatio: '', shareholderName: '', idNumber: "", hrefnFront: '', hrefnBack: '', idcardfileId: '', idcardfilereId: '' };
      this.formData.shareholderInfoDtoList.push(newRow);
    },
    deleteRow(index) {
      this.formData.shareholderInfoDtoList.splice(index, 1);
    },
    addList() {
      const newRows = {
        fileName: '',
        fileUuid: '',
        fileRemark: '',
        fileList: []
      };
      this.listData.push(newRows);
    },
    deleteList(index) {
      this.listData.splice(index, 1);
    },

    handleFrontSuccess(response, file, row) {
      row.hrefnFront = URL.createObjectURL(file.raw);
      row.idcardfileId = response.data.fileUuid
    },
    handleBackSuccess(response, file, row) {
      row.hrefnBack = URL.createObjectURL(file.raw);
      row.idcardfilereId = response.data.fileUuid
    },

    editRow(index) {
      // 执行保存操作，例如将更改发送到服务器等
      console.log('保存行:', index, this.formData.shareholderInfoDtoList[index]);
    },

    beforeAvatarUpload(file) {
      if (!this.checkFile(file)) {
        return false;
      }
    },

    handleLicenseSuccess(response, file) {
      this.ruleForm.hrefn = URL.createObjectURL(file.raw);
      this.formData.licensefileId = response.data.fileUuid
    },
    checkFile(file) {
      //  判断图片类型
      if (this.pic_accept) {
        let picTypeArr = this.pic_accept.split(',');
        let isImage = picTypeArr.some(item => file.type === 'image/' + item.replace(/^\./, ''));
        if (!isImage) {
          this.$modal.msgError('上传图片只能是 （' + this.pic_accept + '） 格式!');
          return false;
        }
      }
      //  判断图片大小
      if (this.pic_maxsize > 0) {
        let isLtNumM = file.size / 1024 / 1024 < this.pic_maxsize;
        if (!isLtNumM) {
          this.$modal.msgError('上传图片大小不能超过 ' + this.pic_maxsize + 'MB!');
          return false;
        }
      }
      return true;
    },
    cleanAgentAreaInfoDtoList(list) {
      if (list.every(item => item === "")) {
        return [];
      }
      return list;
    },
    handleConfirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let ids = this.listData.map(item => item.fileUuid);

          this.formData.realFund = Number((this.formData.realFund * 10000).toFixed(2));
          this.formData.registerFund = Number((this.formData.registerFund * 10000).toFixed(2));
          this.formData.shareholderInfoDtoList.map(item => {
            item.paidCapital = Number((item.paidCapital * 10000).toFixed(2));
            item.paidinFund = Number((item.paidinFund * 10000).toFixed(2));
            item.shareRatio = Number(item.shareRatio);
            return item
          });


          let methods = this.editorsave == 1 ? addAgent : update

          let params = this.editorsave == 1 ? {
            deptName: this.formData.agentName
          } : {};
          if (methods) {
            methods({
              ...this.formData,
              ...params,
              roleKey: this.formData.userName,
              roleName: this.formData.agentName,
              annexId: ids.join(','),
              annexInfoList: this.listData.length ? this.listData.filter(v => v.fileUuid.length > 0).map(item => {
                return {
                  fileName: item.fileName,
                  fileUuid: item.fileUuid,
                  fileRemark: item.fileRemark
                }
              }) : [],
              agentAreaInfoDtoList: this.cleanAgentAreaInfoDtoList(
                this.formData.agentAreaInfoDtoList
              )
            }).then(res => {
              this.$modal.msgSuccess('保存成功');
              this.dialogVisible = false
              this.$emit('clickChange')
            })
          }
        } else {
          return false;
        }
      });
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-table .el-form-item__content {
  margin-left: 0px !important;
}

::v-deep .el-table .el-form-item {
  margin-bottom: 0px;
}
.table-label:before {
  content: "*";
  color: #ff4949;
  margin-right: 4px;
}
.gd_info {
  text-align: right;
  vertical-align: middle;
  float: left;
  font-size: 14px;
  color: #606266;
  font-weight: 700;
  line-height: 40px;
  padding: 0 12px 0 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}
.material {
  display: flex;
}
.tagBox {
  width: 100%;
  min-height: 55px;
  line-height: 55px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}
.agene {
  width: 420px;
  height: 150px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  background-color: #ffffff;
  position: absolute;
  top: 30%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 999;
}
</style>
